package com.ryzx.common.response;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @Project: power-compare
 * @Description: 全局HTTP请求响应体处理器(控制器层)
 * @author: YSR204074
 * @createTime: 2022-06-13 16:11
 * @version: 1.0
 */
@RestControllerAdvice
public class BapGlobalResponseBodyHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(@NonNull MethodParameter methodParameter, @NonNull Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, @NonNull MethodParameter methodParameter, @NonNull MediaType mediaType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> aClass, @NonNull ServerHttpRequest serverHttpRequest,
                                  @NonNull ServerHttpResponse serverHttpResponse) {

        if (o instanceof Integer) {
            return BapResult.success(o);
        }

        if (o instanceof String) {
            return "{\"code\":200,\"data\":\""+o+"\",\"message\":\"success\"}";
        }

        if (o instanceof BapResult) {
            return o;
        }

        return BapResult.success(o);
    }
}
